import { login, logout, captcha } from '@/services/auth';
import { message } from 'antd';
import { routerRedux } from 'dva';
import { stringify } from 'querystring';
import router from 'umi/router';
import { reloadAuthorized } from '@/utils/Authorized';
import { DEFAULT_RESPONE_SUCCESS } from '@/constants';
import { getUrlParameters, setCookie, clearCookie } from '@/utils/utils';

const LoginModel = {
  namespace: 'login',

  state: {
    status: undefined
  },

  effects: {
    *login({ payload }, { call, put }) {
      const { username, password, dispatch, onError } = payload;

      const option = {
        method: 'POST',
        headers: {
          Accept: 'text/html,application/json;q=0.9,image/webp,*/*;q=0.8',
          'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8',
        },
        body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}&captchaSwitch=false`
      };

      const response = yield call(login, { ...option, dispatch, onError });
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const params = getUrlParameters();
        let { redirect } = params;
        const { result = {} } = response;
        const { displayName, access_token, refresh_token, expires_in } = result;

        setCookie('role', 'admin');
        setCookie('displayName', displayName);
        setCookie('access_token', access_token);
        setCookie('refresh_token', refresh_token);
        reloadAuthorized((authority) => { console.info('reloadAuthorized', authority); return 'admin' });

        if (redirect) {
          redirect = decodeURIComponent(redirect);
        }
        yield put(routerRedux.push(redirect || '/'));
      }
    },
    *logout({ payload }, { call, put }) {
      yield call(logout);

      clearCookie('role');
      clearCookie('access_token');
      clearCookie('metabase.SESSION');
      clearCookie('refresh_token');
      clearCookie('displayName');
      reloadAuthorized();

      yield put(routerRedux.push('/user/login'));
    },
    *queryCaptcha({ payload }, { call, put }) {
      const response = yield call(captcha);
      if (response && response.status === DEFAULT_RESPONE_SUCCESS) {
        const { result } = response;

        yield put({
          type: 'changeState',
          payload: { captcha: result }
        });
      } else {
        message.error('获取验证码失败', 1);
      }
    },
  },

  reducers: {
    clear(state, { payload }) {
      return {

      };
    },
    changeState(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    }
  }
};

export default LoginModel;
